<template>
  <div class="register-form">
    <h1 class="title">创建账户</h1>
    <p class="subtitle">加入我们，开始您的旅程</p>

    <el-form :model="form" :rules="rules" ref="registerForm" @submit.prevent="handleRegister">
      <el-form-item prop="username">
        <el-input
            v-model="form.userName"
            placeholder="用户名"
            prefix-icon="User"
            size="large"
        />
      </el-form-item>

      <el-form-item prop="email">
        <el-input
            v-model="form.email"
            placeholder="邮箱"
            prefix-icon="Message"
            size="large"
        />
      </el-form-item>

      <el-form-item prop="password">
        <el-input
            v-model="form.password"
            placeholder="密码"
            type="password"
            show-password
            prefix-icon="Lock"
            size="large"
        />
      </el-form-item>

      <el-form-item prop="code">
        <div class="code-input">
          <el-input
              v-model="form.code"
              placeholder="验证码"
              prefix-icon="Key"
              size="large"
          />
          <el-button
              :disabled="countdown > 0"
              @click="sendCode"
              size="large"
              class="send-code-btn"
          >
            {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
          </el-button>
        </div>
      </el-form-item>

      <el-form-item>
        <el-button
            type="primary"
            native-type="submit"
            size="large"
            :loading="loading"
            class="submit-btn"
        >
          注册
        </el-button>
      </el-form-item>
    </el-form>

    <div class="footer-links">
      <el-link type="info" @click="goToLogin">已有账号？立即登录</el-link>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '@/store/authStore';
import { ElMessage } from 'element-plus';
import Service from '@/router/interceptor.js';  // 新增导入封装的axios实例
const router = useRouter();
const authStore = useAuthStore();

const form = ref({
  userName: '',
  email: '',
  password: '',
  code: ''
});

const loading = ref(false);
const registerForm = ref(null);

const countdown = computed(() => authStore.countdown);
// 修改邮箱验证规则，允许使用其他邮箱
const validateEmail = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入邮箱'));
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
    callback(new Error('请输入有效的邮箱'));
  } else {
    callback();
  }
};

const validatePassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入密码'));
  } else if (value.length < 6) {
    callback(new Error('密码长度不能少于6位'));
  } else {
    callback();
  }
};

const rules = {
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [{ validator: validateEmail, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
};

const sendCode = async () => {
  if (!form.value.email) {
    ElMessage.warning('请输入邮箱');
    return;
  }
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.value.email)) {
    ElMessage.warning('请输入有效的邮箱');
    return;
  }
  
  try {
    const params = new URLSearchParams();
    params.append('email', form.value.email);
    
    const response = await Service.post('/api/user/sendEmail', params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });
    
    if (response.data.success) {
      ElMessage.success('验证码已发送至您的邮箱');
      // 如果需要前端倒计时，可以在这里添加逻辑
      authStore.startCountdown(60); // 假设有60秒倒计时
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '验证码发送失败');
  }
};

const handleRegister = async () => {
  try {
    await registerForm.value.validate();
    loading.value = true;

    const result = await Service.post('/api/user/register',{
      userName: form.value.userName,
      email: form.value.email,
      password: form.value.password,
      code: form.value.code
    });

    if (result.code === 200) {
      ElMessage.success('注册成功');
      router.push('/');
    }
  } catch (error) {
    ElMessage.error('注册失败！');
  } finally {
    loading.value = false;
  }
};

const goToLogin = () => {
  router.push('/');
};
</script>

<style scoped>
.login-form {
  width: 100%;
  animation: fadeIn 0.8s ease;
}

.title {
  font-size: 2.2rem;
  font-weight: 700;
  color: #6c5ce7;
  margin-bottom: 0.5rem;
  text-align: center;
  text-shadow: 0 2px 4px rgba(108,92,231,0.1);
}

.subtitle {
  color: #636e72;
  text-align: center;
  margin-bottom: 2rem;
  font-size: 1rem;
}

.code-input {
  display: flex;
  gap: 10px;
}

.send-code-btn {
  width: 140px;
  flex-shrink: 0;
  background: linear-gradient(135deg,#a6c1ee 0%,#fbc2eb 100%);
  border: none;
  color: white;
}

.submit-btn {
  width: 100%;
  margin-top: 10px;
  background: linear-gradient(135deg,#6c5ce7 0%,#a6c1ee 100%);
  border: none;
  transition: all 0.3s;
}
.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(108,92,231,0.3);
}
.footer-links {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}
@keyframes fadeIn {
  from{
    opacity: 0;
    transform: translateY(10px);
  }
  to{
    opacity: 1;
    transform: translateY(0);
  }
}
</style>